<script setup>
import {reactive, ref, watch} from 'vue'
import {User,Lock} from '@element-plus/icons-vue'
import {login} from "../api/login.js";
//import request from  "../api/index.js"
import { ElMessage } from 'element-plus'
import  {CONFIG} from "../config/index.js";
import {useRouter} from "vue-router";

const loginInfo = reactive({
  username: '',
  password: '',
})
const  router = useRouter()
const loginRef = ref()
// 表单校验功能
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
})
let loginButtonDisabled = ref(true)
watch([
  ()=>loginInfo.username,
  ()=>loginInfo.password,],
  ()=>{
    loginRef.value.validate((valid) => {
      if(valid) {
        loginButtonDisabled.value = false
      }else{
        loginButtonDisabled.value = true
      }
    })
  },
)
// 实现登录的接口 等待结果返回把 async异步修改成同步
const submitForm = ()=>{
  console.log(loginInfo.username,loginInfo.password)
   login(loginInfo.username,loginInfo.password)
      .then((response)=>{
    console.log("登录response: ",response)

        // 把获取到的token存储到浏览器本地
        const  token = response.data.data.token
        window.localStorage.setItem(CONFIG.TOKEN_NAME,token)

        if(response.data.code === 200 ){
          // 登录成功
          ElMessage({
            message: '登录成功',
            type: 'success',
          })

          // 登录成功跳转到首页
          router.replace("/")
        }
  })

}


</script>

<template>
  <!-- 当我们无法控制某个元素时，可以加一层div去控制-->
  <div id="login" style="width: 100vw">
    <el-card  class="box-card">
      <h2 >后台管理系统</h2>
      <el-form
          ref="loginRef"
          :model="loginInfo"
          :rules="rules"
      >
        <el-form-item  prop="username" class="form-item">
          <el-input
              v-model.number="loginInfo.username"
              :prefix-icon="User"
              clearable
              placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item  prop="password" class="form-item">
          <el-input
              v-model="loginInfo.password"
              type="password"
              autocomplete="off"
              :prefix-icon="Lock"
              show-password
              placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item>
          <el-button  class="button-item"  :disabled="loginButtonDisabled"  type="primary" @click="submitForm()" >登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

</template>

<style scoped>
.box-card {
  width: 480px;
  height: 300px;
  margin: 0 auto;

}
.form-item {
  width: 240px;
  margin: 0 auto 20px auto;
}
.button-item {
  margin: 10px auto 10px auto;
}

</style>
